package shinesend.com.cn.downloadapk;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends Activity {


    private LinearLayout linearLayout;

    private String link = "http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1209/17/c1/13902609_1347861942069.jpg";
    private static final int SIZE_GOT = 90;
    int nbThreads = 5;//开启3个线程下载
    private String filename = "experta.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    public Handler mHandle = new Handler( ){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SIZE_GOT:
                    int lngt = (int) msg.obj;
                    launchDownload(lngt);
                    break;
            }
        }
    };
    private void launchDownload(int lngt) {
        //分为多少段;
        int sectionsize = lngt/nbThreads;
        for (int i = 0 ;i<nbThreads;i++){
            LinearLayout lny1 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.progress_item, null);
            ViewHolder vh = new ViewHolder(lny1);
            DownloadAsync thread = new DownloadAsync(vh);
            DownLoadEntity de = new DownLoadEntity();
            de.progress = 0;
            de.fromBits = i * sectionsize;
            de.toBits = (i+1 == nbThreads ? lngt : ((i+1)*sectionsize));
            de.downLink = link;
            de.localPath =getSDCardDownloadFile(filename);
            Log.d("xxx", de.toString());

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                // 运行多线程启动asynctask
                thread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,de);
            } else {
                thread.execute(de);
            }
           linearLayout.addView(lny1);
        }
    }

    private void initView(){
        linearLayout = (LinearLayout) findViewById(R.id.lny);
    }

    // 进度条视图viewholder
    public class ViewHolder implements DownloadAsync.onProgressUpdate {

        public TextView tv_l, tv_r;
        public ProgressBar pb;

        @Override
        public void mainUIUpdate(DownLoadEntity entity) {
            tv_r.setText("" + entity.toBits);
            tv_l.setText("" + entity.fromBits);
            pb.setMax(entity.toBits - entity.fromBits);
            pb.setProgress(entity.progress);
        }

        public ViewHolder(View view) {
            tv_l = (TextView) view.findViewById(R.id.tv_1_left);
            tv_r = (TextView) view.findViewById(R.id.tv_1_right);
            pb = (ProgressBar) view.findViewById(R.id.pb_progression_1);
        }

    }

    //点击事件开始下载
    public void start(View view) {
        linearLayout.removeAllViews();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(link);
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        //获得返回资源的内容的长度
                        int filelength = urlConnection.getContentLength();
                        Message message = mHandle.obtainMessage();
                        message.what = SIZE_GOT;
                        message.obj = filelength;
                        mHandle.sendMessage(message);
                        urlConnection.disconnect();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private String getSDCardDownloadFile(String s) {
        // if sdcard exists...
        String b = Environment.getExternalStorageDirectory().getAbsolutePath();
        File dir = new File(b + "/" + "downs");
        if (!dir.exists())
            dir.mkdirs();
        File file = new File(dir.getAbsolutePath() + "/" + s);
        if (!file.exists())
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return file.getAbsolutePath();
    }
}
